using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using System.Text.RegularExpressions;

namespace IM.Easy.SystemServices.Services
{
    public class SysPostService : AppServices<SysPost>, ISysPostService
    {

        public SysPostService(ISqlSugarClient db) : base(db)
        {

        }

        public SysPost Create(SysPost entity)
        {
            if (!PostValidate(entity, out string msg)) ExceptionUtils.ThrowBusinessException(msg);
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public SysPost GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Context.Queryable<SysPost>().InSingle(id);
        }

        public PageResponse<SysPost> GetPageList(SysPostQueryDto query)
        {
            var queryable = Context.Queryable<SysPost>();
            var exp = Expressionable.Create<SysPost>();
            exp = exp
                   .AndIF(!string.IsNullOrEmpty(query.Name), s => s.Name.Contains(query.Name))
                   .AndIF(!string.IsNullOrEmpty(query.Code), s => s.Code.Contains(query.Code))
                   .AndIF(query.OrgId != default, s => s.OrgId == query.OrgId)
                   .AndIF(query.IsActive != default, s => s.IsActive == query.IsActive);
            var page = queryable
                .Includes(s => s.Org)
                .Includes(s => s.CreatedUser)
                 .Where(exp.ToExpression())
                .ToPageList(query);
            return page;
        }

        public bool UpdatePost(SysPost entity)
        {
            if (!PostValidate(entity, out string msg)) ExceptionUtils.ThrowBusinessException(msg);
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        public bool Delete(params long[] Id)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<SysPost>(Id).ExecuteCommandHasChange();
        }


        /// <summary>
        /// 岗位编码校验
        /// </summary>
        /// <param name="postId">岗位ID（更新时需要排除自身）</param>
        /// <param name="code">岗位编码</param>
        /// <param name="msg">返回校验结果信息</param>
        /// <returns>true：校验通过；false：校验失败</returns>
        private bool CodeValidate(long postId, string code, out string msg)
        {
            msg = string.Empty;

            // 1. 空值或空白字符串检查
            if (string.IsNullOrWhiteSpace(code))
            {
                msg = "岗位编码不能为空";
                return false;
            }

            // 2. （可选）格式检查，例如只允许字母、数字、下划线和短横线
            if (!Regex.IsMatch(code, @"^[a-zA-Z0-9-_]+$"))
            {
                msg = "岗位编码只能包含字母、数字、下划线和短横线";
                return false;
            }

            // 3. 长度检查（根据业务需求进行调整）
            int maxLength = 10;
            if (code.Length > maxLength)
            {
                msg = $"岗位编码长度不能超过 {maxLength} 个字符";
                return false;
            }

            // 4. 使用 SqlSugar 进行重复校验（排除自身角色ID）
            bool exist = Context.Queryable<SysPost>()
                                .Any(r => r.Code == code && r.Id != postId);
            if (exist)
            {
                msg = $"岗位编码 【{code}】 已存在，请更换后重试。";
                return false;
            }

            msg = "校验成功";
            return true;
        }

        /// <summary>
        /// 角色合法性校验
        /// </summary>
        /// <param name="post">角色实体</param>
        /// <param name="msg">返回校验结果信息</param>
        /// <returns>true：校验通过；false：校验失败</returns>
        private bool PostValidate(SysPost post, out string msg)
        {
            if (!CodeValidate(post.Id, post.Code, out msg)) return false;
            msg = "校验成功";
            return true;
        }
    }
}
